<template>
  <div class="video-editing-container">
    <!-- 顶部导航按钮 -->
    <div class="top-nav-buttons">
      <div class="nav-btn return-btn" @click="goToHome">
        <span>🏠 返回主页面</span>
      </div>
      <div class="nav-btn results-btn" @click="showResults = !showResults">
        <span>{{ showResults ? '🎬 返回编辑' : '📁 查看结果' }}</span>
      </div>
    </div>
    
    <!-- 顶部介绍区域 - 10% -->
    <div class="header-section">
      <h1 class="main-title">🎬 AI智能视频剪辑工具</h1>
      <p class="subtitle">一站式视频处理解决方案 - 文字转视频、智能分割、字幕添加、流畅转场</p>
      <div class="feature-highlights">
        <span class="highlight-tag">🚀 智能AI驱动</span>
        <span class="highlight-tag">⚡ 快速处理</span>
        <span class="highlight-tag">🎯 简单易用</span>
      </div>
    </div>

    <!-- 功能按钮区域 - 10%~30% -->
    <div class="function-buttons-section">
      <div class="buttons-grid">
        <button 
          @click="activeFunction = 'text-to-video'" 
          :class="['function-btn', { active: activeFunction === 'text-to-video' }]"
        >
          <div class="btn-icon">📝</div>
          <div class="btn-text">
            <span class="btn-title">文字视频生成</span>
            <span class="btn-desc">输入文字自动生成视频</span>
          </div>
        </button>

        <button 
          @click="activeFunction = 'video-split'" 
          :class="['function-btn', { active: activeFunction === 'video-split' }]"
        >
          <div class="btn-icon">✂️</div>
          <div class="btn-text">
            <span class="btn-title">视频分割</span>
            <span class="btn-desc">精准切割视频片段</span>
          </div>
        </button>

        <button 
          @click="activeFunction = 'add-text'" 
          :class="['function-btn', { active: activeFunction === 'add-text' }]"
        >
          <div class="btn-icon">🎯</div>
          <div class="btn-text">
            <span class="btn-title">添加文字</span>
            <span class="btn-desc">为视频添加字幕水印</span>
          </div>
        </button>

        <button 
          @click="activeFunction = 'video-transition'" 
          :class="['function-btn', { active: activeFunction === 'video-transition' }]"
        >
          <div class="btn-icon">🎭</div>
          <div class="btn-text">
            <span class="btn-title">视频转场</span>
            <span class="btn-desc">添加炫酷转场效果</span>
          </div>
        </button>
      </div>
    </div>

    <!-- 功能区域 - 70%~100% -->
    <div class="function-area">
      <!-- 文字视频生成 -->
      <div v-if="activeFunction === 'text-to-video'" class="function-panel">
        <h2 class="panel-title">📝 文字视频生成</h2>
        <div class="panel-content">
          <div class="input-group">
            <label>输入文字内容</label>
            <textarea 
              v-model="textToVideoForm.text" 
              placeholder="请输入要转换为视频的文字内容..."
              rows="4"
            ></textarea>
          </div>
          
          <div class="input-group">
            <label>提示词优化</label>
            <textarea 
              v-model="textToVideoForm.prompt" 
              placeholder="可选：添加更多细节描述以获得更好的视频效果..."
              rows="2"
            ></textarea>
          </div>

          <div class="action-buttons">
            <button class="primary-btn" @click="generateTextToVideo">
              🚀 开始生成
            </button>
            <button class="secondary-btn" @click="resetTextToVideo">
              🔄 重置
            </button>
          </div>
        </div>
      </div>

      <!-- 视频分割 -->
      <div v-if="activeFunction === 'video-split'" class="function-panel">
        <h2 class="panel-title">✂️ 视频分割</h2>
        <div class="panel-content">
          <div class="upload-area">
            <div class="upload-box">
              <input type="file" accept="video/*" @change="handleVideoUpload" hidden ref="videoFileInput">
              <button class="upload-btn" @click="$refs.videoFileInput.click()">
                📁 选择视频文件
              </button>
              <p class="upload-tip">支持 MP4、AVI、MOV 等格式</p>
            </div>
          </div>

          <div v-if="videoSplitForm.videoFile" class="split-options">
            <div class="input-group">
              <label>分割方式</label>
              <div class="radio-group">
                <label class="radio-option">
                  <input type="radio" v-model="videoSplitForm.splitType" value="time">
                  <span>按时间分割</span>
                </label>
                <label class="radio-option">
                  <input type="radio" v-model="videoSplitForm.splitType" value="scene">
                  <span>按场景分割</span>
                </label>
              </div>
            </div>

            <div v-if="videoSplitForm.splitType === 'time'" class="time-input">
              <div class="input-group">
                <label>每段时长（秒）</label>
                <input type="number" v-model="videoSplitForm.duration" min="1" max="300">
              </div>
            </div>

            <div class="action-buttons">
              <button class="primary-btn" @click="splitVideo">
                ✂️ 开始分割
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- 添加文字 -->
      <div v-if="activeFunction === 'add-text'" class="function-panel">
        <h2 class="panel-title">🎯 添加文字</h2>
        <div class="panel-content">
          <div class="upload-area">
            <div class="upload-box">
              <input type="file" accept="video/*" @change="handleVideoForText" hidden ref="textVideoInput">
              <button class="upload-btn" @click="$refs.textVideoInput.click()">
                📁 选择视频文件
              </button>
            </div>
          </div>

          <div v-if="addTextForm.videoFile" class="text-options">
            <div class="input-group">
              <label>文字内容</label>
              <textarea v-model="addTextForm.text" placeholder="请输入要添加的文字..." rows="3"></textarea>
            </div>

            <div class="form-row">
              <div class="input-group">
                <label>字体大小</label>
                <input type="range" v-model="addTextForm.fontSize" min="12" max="72" class="slider">
                <span>{{ addTextForm.fontSize }}px</span>
              </div>

              <div class="input-group">
                <label>文字颜色</label>
                <input type="color" v-model="addTextForm.textColor" class="color-picker">
              </div>
            </div>

            <div class="input-group">
              <label>文字位置</label>
              <select v-model="addTextForm.position">
                <option value="top-left">左上角</option>
                <option value="top-center">顶部居中</option>
                <option value="top-right">右上角</option>
                <option value="center">中心</option>
                <option value="bottom-left">左下角</option>
                <option value="bottom-center">底部居中</option>
                <option value="bottom-right">右下角</option>
              </select>
            </div>

            <div class="action-buttons">
              <button class="primary-btn" @click="addTextToVideo">
                🎯 添加文字
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- 视频转场 -->
      <div v-if="activeFunction === 'video-transition'" class="function-panel">
        <h2 class="panel-title">🎭 视频转场</h2>
        <div class="panel-content">
          <div class="upload-area">
            <div class="upload-box">
              <input type="file" accept="video/*" multiple @change="handleTransitionVideos" hidden ref="transitionVideoInput">
              <button class="upload-btn" @click="$refs.transitionVideoInput.click()">
                📁 选择多个视频文件
              </button>
              <p class="upload-tip">选择2个或更多视频文件</p>
            </div>
          </div>

          <div v-if="transitionForm.videos.length > 1" class="transition-options">
            <!-- 转场类型选择 -->
            <div class="input-group">
              <label>转场类型</label>
              <div class="transition-type-selector">
                <label class="radio-option">
                  <input type="radio" v-model="transitionForm.transitionCategory" value="fade">
                  <span>🌅 交叉淡入淡出</span>
                </label>
                <label class="radio-option">
                  <input type="radio" v-model="transitionForm.transitionCategory" value="slide">
                  <span>➡️ 滑动转场</span>
                </label>
              </div>
            </div>

            <!-- 交叉淡入淡出选项 -->
            <div v-if="transitionForm.transitionCategory === 'fade'" class="fade-options">
              <div class="input-group">
                <label>淡入淡出类型</label>
                <select v-model="transitionForm.fadeType">
                  <option value="cross">交叉淡入淡出</option>
                  <option value="fadeIn">淡入</option>
                  <option value="fadeOut">淡出</option>
                  <option value="dissolve">溶解效果</option>
                </select>
              </div>
              
              <div class="input-group">
                <label>透明度曲线</label>
                <select v-model="transitionForm.fadeCurve">
                  <option value="linear">线性</option>
                  <option value="easeIn">缓入</option>
                  <option value="easeOut">缓出</option>
                  <option value="easeInOut">缓入缓出</option>
                </select>
              </div>
            </div>

            <!-- 滑动转场选项 -->
            <div v-if="transitionForm.transitionCategory === 'slide'" class="slide-options">
              <div class="input-group">
                <label>滑动方向</label>
                <div class="slide-direction-grid">
                  <label class="direction-option">
                    <input type="radio" v-model="transitionForm.slideDirection" value="left">
                    <span>⬅️ 向左</span>
                  </label>
                  <label class="direction-option">
                    <input type="radio" v-model="transitionForm.slideDirection" value="right">
                    <span>➡️ 向右</span>
                  </label>
                  <label class="direction-option">
                    <input type="radio" v-model="transitionForm.slideDirection" value="up">
                    <span>⬆️ 向上</span>
                  </label>
                  <label class="direction-option">
                    <input type="radio" v-model="transitionForm.slideDirection" value="down">
                    <span>⬇️ 向下</span>
                  </label>
                </div>
              </div>
              
              <div class="input-group">
                <label>滑动类型</label>
                <select v-model="transitionForm.slideType">
                  <option value="push">推动</option>
                  <option value="cover">覆盖</option>
                  <option value="uncover">揭开</option>
                  <option value="slideOver">滑过</option>
                </select>
              </div>
              
              <div class="input-group">
                <label>滑动速度</label>
                <input type="range" v-model="transitionForm.slideSpeed" min="0.5" max="3" step="0.1" class="slider">
                <span>{{ transitionForm.slideSpeed }}s</span>
              </div>
            </div>

            <div class="input-group">
              <label>转场时长（秒）</label>
              <input type="range" v-model="transitionForm.duration" min="0.5" max="3" step="0.1" class="slider">
              <span>{{ transitionForm.duration }}s</span>
            </div>

            <div class="video-preview">
              <h4>视频顺序</h4>
              <div class="video-list">
                <div v-for="(video, index) in transitionForm.videos" :key="index" class="video-item">
                  <span class="video-number">{{ index + 1 }}</span>
                  <span class="video-name">{{ video.name }}</span>
                </div>
              </div>
            </div>

            <div class="action-buttons">
              <button class="primary-btn" @click="applyTransition">
                🎭 应用转场
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 进度条组件 -->
    <div v-if="processing" class="processing-overlay">
      <div class="processing-content">
        <div class="spinner"></div>
        <p>{{ processingMessage }}</p>
        <div class="progress-bar">
          <div class="progress-fill" :style="{ width: progress + '%' }"></div>
        </div>
      </div>
    </div>

      <!-- 结果查看区域 -->
      <div v-if="showResults" class="results-section">
        <h2>📁 生成的视频文件</h2>
        <div v-if="videoFiles.length === 0" class="no-files">
          <p>暂无生成的视频文件</p>
          <p class="hint">请先在上方进行视频编辑操作</p>
        </div>
        <div v-else class="file-list">
          <div v-for="file in videoFiles" :key="file.filename" class="file-item">
            <div class="file-info">
              <h3>{{ file.filename }}</h3>
              <p>大小: {{ formatFileSize(file.size) }}</p>
              <p>创建时间: {{ formatDate(file.created_time) }}</p>
            </div>
            <div class="file-actions">
              <button @click="previewVideo(file.filename)" class="btn-preview">预览</button>
              <button @click="downloadVideo(file.filename)" class="btn-download">下载</button>
            </div>
          </div>
        </div>
        <button @click="refreshFiles" class="btn-refresh">🔄 刷新列表</button>
      </div>
    </div>
  </template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()

// 当前激活的功能
const activeFunction = ref('text-to-video')

// 处理状态
const processing = ref(false)
const processingMessage = ref('')
const progress = ref(0)
const showResults = ref(false)
const videoFiles = ref([])

// 表单数据
const textToVideoForm = reactive({
  text: '',
  prompt: ''
})

const videoSplitForm = reactive({
  videoFile: null,
  splitType: 'time',
  duration: 10
})

const addTextForm = reactive({
  videoFile: null,
  text: '',
  fontSize: 24,
  textColor: '#ffffff',
  position: 'center'
})

const transitionForm = reactive({
  videos: [],
  transitionCategory: 'fade',
  duration: 1,
  // 交叉淡入淡出参数
  fadeType: 'cross',
  fadeCurve: 'easeInOut',
  // 滑动转场参数
  slideDirection: 'left',
  slideType: 'push',
  slideSpeed: 1
})

// 获取视频文件列表
const refreshFiles = async () => {
  try {
    const response = await fetch('http://localhost:5000/api/video/results')
    const data = await response.json()
    if (data.success) {
      videoFiles.value = data.files || []
    }
  } catch (err) {
    console.error('获取文件列表失败:', err)
  }
}

// 预览视频
const previewVideo = (filename) => {
  window.open(`http://localhost:5000/api/video/preview/${filename}`, '_blank')
}

// 下载视频
const downloadVideo = (filename) => {
  window.open(`http://localhost:5000/api/video/download/${filename}`, '_blank')
}

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 格式化日期
const formatDate = (timestamp) => {
  const date = new Date(timestamp * 1000)
  return date.toLocaleString('zh-CN')
}

// 监听显示结果页面变化
import { watch } from 'vue'
watch(showResults, (newVal) => {
  if (newVal) {
    refreshFiles()
  }
})

// 文件处理函数
const handleVideoUpload = (event) => {
  const file = event.target.files[0]
  if (file) {
    videoSplitForm.videoFile = file
  }
}

const handleVideoForText = (event) => {
  const file = event.target.files[0]
  if (file) {
    addTextForm.videoFile = file
  }
}

const handleTransitionVideos = (event) => {
  const files = Array.from(event.target.files)
  transitionForm.videos = files
}

// 功能处理函数
const generateTextToVideo = async () => {
  if (!textToVideoForm.text.trim()) {
    alert('请输入文字内容')
    return
  }

  processing.value = true
  processingMessage.value = '正在生成AI视频...'
  progress.value = 0

  try {
    // 构建完整的提示词
    let fullPrompt = textToVideoForm.text;
    if (textToVideoForm.prompt.trim()) {
      fullPrompt += "。" + textToVideoForm.prompt;
    }

    const response = await fetch('http://localhost:5000/api/video/text-to-video', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        text: fullPrompt
      })
    })
    
    const data = await response.json()
    
    if (data.success) {
      alert('AI视频生成完成！')
      refreshFiles() // 刷新文件列表
    } else {
      alert('AI视频生成失败：' + data.error)
    }
  } catch (error) {
    alert('请求失败：' + error.message)
  } finally {
    processing.value = false
  }
}

const splitVideo = async () => {
  if (!videoSplitForm.videoFile) {
    alert('请选择视频文件')
    return
  }

  processing.value = true
  processingMessage.value = '正在上传并分割视频...'
  
  try {
      const formData = new FormData()
      formData.append('video', videoSplitForm.videoFile)
      formData.append('split_type', videoSplitForm.splitType)
      formData.append('duration', videoSplitForm.duration)

    const response = await fetch('http://localhost:5000/api/video/split-video', {
      method: 'POST',
      body: formData
    })
    
    const data = await response.json()
    
    if (data.success) {
      alert(`视频分割完成！生成了 ${data.count} 个片段`)
      result.value = data.video_paths
    } else {
      alert('视频分割失败：' + data.error)
    }
  } catch (error) {
    alert('上传失败：' + error.message)
  } finally {
    processing.value = false
  }
}

const addTextToVideo = async () => {
  if (!addTextForm.videoFile || !addTextForm.text.trim()) {
    alert('请填写完整信息')
    return
  }

  processing.value = true
  processingMessage.value = '正在上传并添加文字...'
  
  try {
    const formData = new FormData()
    formData.append('video', addTextForm.videoFile)
    formData.append('text', addTextForm.text)
    formData.append('font_size', addTextForm.fontSize)
    formData.append('text_color', addTextForm.textColor)
    formData.append('position', addTextForm.position)

    const response = await fetch('http://localhost:5000/api/video/add-text', {
      method: 'POST',
      body: formData
    })
    
    const data = await response.json()
    
    if (data.success) {
      alert('文字添加完成！')
      result.value = data.video_path
    } else {
      alert('文字添加失败：' + data.error)
    }
  } catch (error) {
    alert('上传失败：' + error.message)
  } finally {
    processing.value = false
  }
}

const applyTransition = async () => {
  if (transitionForm.videos.length < 2) {
    alert('请至少选择两个视频文件')
    return
  }

  processing.value = true
  processingMessage.value = '正在上传并应用转场效果...'
  
  try {
    const formData = new FormData()
    
    // 添加多个视频文件
    transitionForm.videos.forEach((file, index) => {
      formData.append(`video${index + 1}`, file)
    })
    
    formData.append('transition_category', transitionForm.transitionCategory)
    formData.append('duration', transitionForm.duration)
    
    if (transitionForm.transitionCategory === 'fade') {
      formData.append('fade_type', transitionForm.fadeType)
      formData.append('fade_curve', transitionForm.fadeCurve)
    } else if (transitionForm.transitionCategory === 'slide') {
      formData.append('slide_direction', transitionForm.slideDirection)
      formData.append('slide_type', transitionForm.slideType)
      formData.append('slide_speed', transitionForm.slideSpeed)
    }

    const response = await fetch('http://localhost:5000/api/video/apply-transition', {
      method: 'POST',
      body: formData
    })
    
    const data = await response.json()
    
    if (data.success) {
      alert('转场效果应用完成！')
      result.value = data.video_path
    } else {
      alert('转场效果应用失败：' + data.error)
    }
  } catch (error) {
    alert('上传失败：' + error.message)
  } finally {
    processing.value = false
  }
}

const resetTextToVideo = () => {
  textToVideoForm.text = ''
  textToVideoForm.prompt = ''
}

// 返回首页
const goToHome = () => {
  router.push('/')
}
</script>

<style scoped>
@import '../assets/VideoEditing.css';
</style>
